/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shooter;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

/**
 *
 * @author Unni Vemanchery Mana
 */
public class SpriteExplode {

    private String spriteImage;
    private SpriteBatch batch;
    private Texture texture;
    private Sprite sprite;
    private long time = 0;
    private boolean isAnimated = false;
    SpriteObject[] spirteObjects;
    private int objectCount = 25;

    public SpriteExplode(String spriteImg) {
        loadSpriteObject(spriteImg);
    }

    private void loadSpriteObject(String spriteImg) {
        spriteImage = (spriteImg == null) ? "img1.png" : spriteImg;
        Texture.setEnforcePotImages(false);
        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal(spriteImage));
        sprite = new Sprite(texture);
        sprite.setSize(5, 5);
        initialize();
    }

    public void setAnimated(boolean isAnimated) {
        this.isAnimated = isAnimated;
        time = System.currentTimeMillis();
    }

    public void initialize() {
        spirteObjects = new SpriteObject[objectCount];
        for (int i = 0; i < spirteObjects.length; i++) {
            SpriteObject so = new SpriteObject();
            so.x = 140;
            so.y = 130;
            so.scaleX = (float) (0.2 + Math.random() * 0.4);
            so.scaleY = so.scaleX;
            so.yVelocity = (float) Math.random() * 4 - 5;
            so.xVelocity = (float) Math.random() * 6 - 3;
            so.timeToLive += (float) Math.random() * 6;
            spirteObjects[i] = so;
        }
    }

    public void updatePosition(float x, float y) {
        int i = 0;
        for(SpriteObject so : spirteObjects) {
           so.x = x;
           so.y = y;
           spirteObjects[i] = so;
           i++;
        }
    }

    public void drawSpriteExplosion(SpriteBatch batch) {
            for (SpriteObject so : spirteObjects) {
                so.y += so.yVelocity;
                so.x += so.xVelocity;
                so.yVelocity += 0.09;
                if((System.currentTimeMillis() - time) >= so.timeToLive) {
                    so.y = -1;
                    so.x = -1;
                    return;
                }
                //sprite.setPosition(so.x, so.y);
                //sprite.draw(batch);
                batch.draw(texture, so.x, so.y);
            }
    }

    private class SpriteObject {

        float x, y = 0;
        float scaleX, scaleY = 0;
        private float yVelocity = 0;
        private float xVelocity = 0;
        private long timeToLive = 400;
        private boolean isVisible = false;
    }
}
